<?php
require APPPATH.'libraries/ApiController.php';
class order extends ApiController {
	public function __construct()
	{
		parent::__construct();
	}
	
	//创建订单
	public function create(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			["uid",true,"会员ID"],
			["username",false,"用户名","散客"],
			["ordercode",true,"订单号"],
			["paytype",true,"支付方式"],
			["finalsum",true,"订单总额"],
			["buylist",true,"订单商品"],
			],'post');
			
			$data["sum"]=$data["finalsum"];
			unset($data["finalsum"]);
			$paytype=json_decode($data["paytype"],true);
			
			//判断是否会员结算
			if($data["uid"]==-1){ //非会员
				//创建订单数据
				$data["shopid"]=$token["shopid"];
				$data["afterrmb"]=0;
				$this->db->insert("payment_rmb",$data);
				$resdata=array(
					"username"=>$data["username"],
					"ordercode"=>$data["ordercode"],
					"paytype"=>$paytype,
					"sumrmb"=>(float)$data["sum"],
					"afterscore"=>0,
					"afterrmb"=>0,
					"createtime"=>date('Y-m-d H:i:s')
				);
				$this->WRITE("code",1);				
				$this->WRITE("data",$resdata);
				$this->WRITE("msg","操作成功!");
				$this->RESPONSE();
 
			}else{
				if($paytype["ptid"]==2){ //使用余额支付
					//查询用户余额
					$this->db->where("uid",$data["uid"]);
					$this->db->where("shopid",$token["shopid"]);
					$this->db->select("uid,username,money,score");
					$user=$this->db->get("user")->row_array();
					
					if((float)$user["money"]<(float)$data["sum"]){
						$this->WRITE("code",0);
						$this->WRITE("msg","该会员余额不足!");
						$this->RESPONSE();
						return;
					}
					$beforermb=$user["money"];
					$afterrmb=$beforermb-$data["sum"];
					$afterscore=$user["score"];
					
					
					//创建订单数据
					$data["shopid"]=$token["shopid"];
					$data["afterrmb"]=$afterrmb;
					$this->db->insert("payment_rmb",$data);
					
					 
					
					$this->db->where("uid",$data["uid"]);
					$this->db->update("user",array("money"=>$afterrmb));
					
					$resdata=array(
					"username"=>$data["uid"]==-1? "散客":$data["username"],
					"ordercode"=>$data["ordercode"],
					"paytype"=>$paytype["pttitle"],
					"sumrmb"=>(float)$data["sum"],
					"afterrmb"=>(float)$afterrmb,
					"createtime"=>date('Y-m-d H:i:s')
					);
					$this->WRITE("code",1);				
					$this->WRITE("data",$resdata);
					$this->WRITE("msg","操作成功!");
					$this->RESPONSE();
				}else if($paytype["ptid"]=="积分"){
					
					
					
				}
				
				
			}
 
		}
	}
}